package com.hskn.hss.module.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.entity.TreeEntity;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.entity.UserFull;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2020-11-16
 */
@Api(tags = {"-user"}, description = "用户档案")
@Slf4j
@RestController
@RequestMapping("/hss/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "loginByPwd", method = RequestMethod.POST)
    public AjaxResult<Object> loginByPwd(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject json = userService.loginByPwd(params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("登录失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "user", idKey = "uid", bean = User.class, beanMapper = UserMapper.class, names = "account", isCompare = false)
    @RequestMapping(value = "modifyPwd", method = RequestMethod.POST)
    public AjaxResult<Object> modifyPwd(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            userService.modifyPwd(params);
            return AjaxResult.success();
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("修改失败，请稍后再试");
        }
    }


    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public AjaxResult<Object> detail(HttpServletRequest request) {
        try {
            UserFull user = userService.detail();
            if (StringUtils.isEmpty(user)) {
                return AjaxResult.fail("用户信息不存在，请联系管理员或重新登录再试");
            }
            user.setPassword(null);
            user.setSalt(null);
            return AjaxResult.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.INSERT, tableName = "user", bean = User.class, beanMapper = UserMapper.class, names = "account")
    @RequestMapping(value = "admin/addUser", method = RequestMethod.POST)
    public AjaxResult<Object> addUser(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            userService.addUser(params);
            return AjaxResult.success("添加成功");
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            Throwable cause = e.getCause();
            if (cause instanceof SQLIntegrityConstraintViolationException) {
                e.printStackTrace();
                log.error("报错ERROR", e);
                return AjaxResult.fail("添加失败，账号已存在");
            }
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("添加失败，请稍后再试");
        }
    }

    @RequestMapping(value = "admin/list", method = RequestMethod.POST)
    public AjaxResult<Object> list(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            JSONObject json = userService.mList(params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "user", idKey = "uid", bean = User.class, beanMapper = UserMapper.class, names = "account", isCompare = false)
    @RequestMapping(value = "admin/update", method = RequestMethod.POST)
    public AjaxResult<Object> aUpdate(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            userService.mUpdate(params);
            return AjaxResult.success();
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("更新失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "user", idKey = "ids", bean = User.class, beanMapper = UserMapper.class, names = "account")
    @ApiOperation(value = "批量修改接口", notes = "批量修改")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = User.class)
    })
    @RequestMapping(value = "admin/listUpdate", method = RequestMethod.POST)
    public AjaxResult<Object> listUpdate(@RequestBody @Validated User user) {
        try {
            //todo 套接口通知一下大家
            userService.listUpdate(user);
            return AjaxResult.success();
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("更新失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "user", idKey = "uid", bean = User.class, beanMapper = UserMapper.class, names = "account")
    @RequestMapping(value = "admin/del", method = RequestMethod.POST)
    public AjaxResult<Object> aDel(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            userService.mDel(params);
            return AjaxResult.success();
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "user", idKey = "ids", bean = User.class, beanMapper = UserMapper.class, names = "account")
    @ApiOperation(value = "批量删除接口", notes = "批量删除")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = User.class)
    })
    @RequestMapping(value = "deletebatchbyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebatchbyid(@RequestBody @Validated User user, HttpServletRequest request) {

        try {
            return userService.deletebatchbyid(user);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @RequestMapping(value = "admin/tree", method = RequestMethod.POST)
    public AjaxResult<Object> tree(HttpServletRequest request) {
        try {
            List<TreeEntity> userTree = userService.userTree();
            return AjaxResult.success(userTree);
        } catch (HssException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("查询失败，请稍后再试");
        }
    }

    @PostMapping(value = "processingIsAdminUser")
    public AjaxResult processingIsAdminUser() {
        try {
            userService.processingIsAdminUser();
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("查询失败，请稍后再试");
        }
    }

}

